package com.es.test.service;

/**
 * @author django
 * @date 2024/2/4
 * @description TODO
 */

import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.BitSet;
import java.util.List;

@Service
public class BitSetService {

    private final RedisTemplate<String, Object> redisTemplate;

    public BitSetService(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void generateAndSetBitSet(String bitSetKey1, String bitSetKey2, String resultKey,
                                     int totalDataPoints, int positiveSamples1, int positiveSamples2) {

        // Generate and set two BitSet
        BitSet bitSet1 = generateAndSetBitSet(totalDataPoints, positiveSamples1);
        BitSet bitSet2 = generateAndSetBitSet(totalDataPoints, positiveSamples2);

        // Set the BitSet in Redis
        redisTemplate.opsForValue().set(bitSetKey1, bitSet1);
        redisTemplate.opsForValue().set(bitSetKey2, bitSet2);

        // Execute bitop operation to get intersection and store in resultKey
        redisTemplate.execute((RedisCallback<Void>) connection -> {
            connection.bitOp(RedisStringCommands.BitOperation.AND,
                    resultKey.getBytes(),
                    bitSetKey1.getBytes(),
                    bitSetKey2.getBytes());
            return null;
        });
    }

    public boolean isBitSet(String bitSetKey, int indexToCheck) {
        BitSet bitSet = (BitSet) redisTemplate.opsForValue().get(bitSetKey);
        return bitSet != null && bitSet.get(indexToCheck);
    }

    private BitSet generateAndSetBitSet(int totalDataPoints, int positiveSamples) {
        BitSet bitSet = new BitSet(totalDataPoints);
        for (int i = 0; i < positiveSamples; i++) {
            int randomIndex = i;  // In a real-world scenario, generate random indices
            bitSet.set(randomIndex);
        }
        return bitSet;
    }
}
